

var AWSearch = function(dev_token, xslt, options){
  return new AWSearch.Search(dev_token, xslt, options);
};

AWSearch.results = {};
AWSearch.callbacks = {};

AWSearch.Utils = {
  extend: function(destination, source) {
    for (property in source) {
      destination[property] = source[property];
    }
    return destination;
  },

  bind: function(method, object) {
    return function() {
      return method.apply(object, arguments);
    }
  }
};

AWSearch.Search = function(){ this.initialize.apply(this, arguments); };
AWSearch.Search.prototype = {
  initialize: function(dev_token, xslt, options){
    if(!dev_token)
      throw('dev_token is required.');
    if(!xslt)
      throw("xslt's uri is required.");
    this.dev_token = dev_token;
    this.xslt = xslt;
    this.setOptions(options);
  },

  setOptions: function(options) {
    this.options = {
      asid: 'm1ck-20',
      searchType: 'Keywords',
      mode: 'DVD',
      type: 'lite',
      page: 1,
      locale: 'us'
    };
    AWSearch.Utils.extend(this.options, options || {});
  },

  search: function(keyword){
    if(!keyword)
      return false;
    var script = document.createElement('script');
    script.charset = 'UTF-8';
    var name = '';
    with(this.options){
    //  script.src = 'http://xml-us.amznxslt.com/onca/xml3?t=' + asid + '&dev-t=' + this.dev_token + '&' + searchType + '=' + encodeURI(keyword) + '&mode=' + mode + '&type=' + type + '&page=' + page + '&f=' + this.xslt + '&locale=' + locale;
        script.src = 'http://xml-us.amznxslt.com/onca/xml?Service=AWSECommerceService&Operation=ItemSearch&Style=' + this.xslt + '&ContentType=text%2Fxml&SubscriptionId=' + this.dev_token + '&AssociateTag=m1ck-20&Validate=False&SearchIndex=' + mode +  '&' + searchType + '=' + encodeURI(keyword) + '&ResponseGroup=Small&CallBack=1';


    name = mode + '_' + keyword + '_' + page;
   // document.getElementById('result1').innerHTML=script.src;
    }
    AWSearch.callbacks[name] = AWSearch.Utils.bind(function(result){
      this.count = result.count;
      if(this.options.onSuccess)
        AWSearch.Utils.bind(this.options.onSuccess, this)(result);
    }, this);

    if(typeof this.options.onCreate == 'function')
      this.options.onCreate();
    document.body.appendChild(script);
  }
};
